<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<c:set var="home" value="${pageContext.request.contextPath}" />
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
	content="width=device-width, initial-scale=1, maximum-scale=1">
<title>文章管理</title>
<jsp:include page="../../../common/common.jsp"></jsp:include>
<style>
.layui-table-cell {
	height: 36px;
	line-height: 36px;
}
.layui-table {
	overflow-x: true;
	overflow-y: true;
}
</style>
</head>
<body>

	<!-- 新增 -->
	<div class="layui-fluid" id="pop" style="display: none">
		<div class="layui-row">
			<form class="layui-form" style="padding: 8px 8px">
				<div class="layui-col-md4 layui-form-item">
					<label class="layui-form-label">标题</label>
					<div class="layui-input-block">
						<input type="text" name="title" autocomplete="off"
							placeholder="标题" class="layui-input" lay-verify="required">
					</div>
				</div>
				<div class="layui-col-md4 layui-form-item">
					<label class="layui-form-label">作者</label>
					<div class="layui-input-block">
						<input type="text" name="author" autocomplete="off"
							placeholder="作者" class="layui-input" lay-verify="required">
					</div>
				</div>
				<div class="layui-col-md4 layui-form-item">
					<label class="layui-form-label">摘要</label>
					<div class="layui-input-block">
						<input type="text" name="digest" autocomplete="off"
							placeholder="摘要" class="layui-input" lay-verify="required">
					</div>
				</div>
				<div class="layui-col-md4 layui-form-item">
					<label class="layui-form-label">内容</label>
					<!-- context -->
					<div class="layui-input-block">
						<script type='text/plain' id="editor" name="context"></script>
					</div>
				</div>
				<div class="layui-col-md4 layui-form-item">
					<div class="layui-input-block">
						<button class="layui-btn layui-primary" id="addUser"
							data-type="reload" lay-submit lay-filter="addSmt">
							<i class="layui-icon" style="font-size: 20px;"></i>添加
						</button>
					</div>
				</div>
			</form>
		</div>
	</div>

	<!-- 修改 -->
	<div class="layui-fluid" id="modifyPop" style="display: none">
		<div class="layui-row">
			<form class="layui-form" style="padding: 8px 8px" id="modForm"
				lay-filter="modForm">
				<div class="layui-col-md4 layui-form-item">
					<label class="layui-form-label">标题</label>
					<div class="layui-input-block">
						<input type="text" name="title" autocomplete="off"
							placeholder="标题" class="layui-input" lay-verify="required">
					</div>
				</div>
				<div class="layui-col-md4 layui-form-item">
					<label class="layui-form-label">作者</label>
					<div class="layui-input-block">
						<input type="text" name="author" autocomplete="off"
							placeholder="作者" class="layui-input" lay-verify="required">
					</div>
				</div>
				<div class="layui-col-md4 layui-form-item">
					<label class="layui-form-label">摘要</label>
					<div class="layui-input-block">
						<input type="text" name="digest" autocomplete="off"
							placeholder="摘要" class="layui-input" lay-verify="required">
					</div>
				</div>
				<div class="layui-col-md4 layui-form-item">
					<label class="layui-form-label">内容</label>
					<!-- context -->
					<div class="layui-input-block">
						<script type='text/plain' id="editor1" name="context"></script>
					</div>
				</div>
				<div class="layui-col-md4 layui-form-item">
					<div class="layui-input-block">
						<button class="layui-btn layui-primary" id="addUser"
							data-type="reload" lay-submit lay-filter="modifySmt">
							<i class="layui-icon" style="font-size: 20px;"></i>修改
						</button>
					</div>
				</div>
				<input type="hidden" name="articleId" />
				<input type="hidden" name="context" />
			</form>
		</div>
	</div>
	
	<!-- 查看 -->
	<table class="layui-table" id="detailPop" style="display: none">
		<thead>
		  <tr>
		    <th>标题</th>
		    <th>作者</th>
		    <th>摘要</th>
		  </tr> 
		</thead>
		<tbody>
		  <tr>
		    <td id="_title"></td>
		    <td id="_author"></td>
		    <td id="_digest"></td>
		  </tr>
		</tbody>
	</table>
	
	<form class="layui-form" style="padding: 15px 15px">
		<div class="layui-input-inline">
			<input type="text" name="title" autocomplete="off"
				placeholder="标题" class="layui-input" lay-verify="required">
		</div>
		<div class="layui-input-inline " style="width: 90px">
			<button class="layui-btn" id="searchEmailCompany" data-type="reload"
				lay-submit lay-filter="smt">
				<i class="layui-icon" style="font-size: 20px;"></i> 搜索
			</button>
		</div>
	</form>
	
	<input type="hidden" id="_permission" value="${permission}"/>
	
	<script type="text/html" id="toolbarDemo">
		<button class="layui-btn layui-btn-normal" lay-event="add" id="_add">添加</button>
	</script>
	
	<table id="demo" lay-filter="opt"></table>

	<script type="text/html" id="barDemo">
		<div class="layui-table-fixed layui-table-fixed-l">
			<div class="layui-table-cell laytable-cell-1-0-10">
				<button class="layui-btn layui-btn-primary layui-btn-xs _detail" lay-event="detail">查看</button> 
				<button class="layui-btn layui-btn-xs _update" lay-event="update">编辑</button> 
				<button class="layui-btn layui-btn-danger layui-btn-xs _delete" lay-event="delete">删除</button> 
			</div>
		</div>
	</script>
	
	<script>
	//富文本
	function afluentTextEditor(id){
		editor = new UE.ui.Editor({initialFrameHeight:200,initialFrameWidth:640,toolbars:[["undo","redo",
																							   "fontsize","fontfamily",
																							   "bold","italic",
																							   "underline","justifyleft",
																							   "justifycenter","justifyright",
																							   "justifyjustify","formatmatch",
																							   "removeformat","emotion",
																							   'time','date','simpleupload', 
	        																			       'link','unlink','insertvideo',
	        																			       'imagenone','imageleft',
	        																			       'imageright','attachment',
	        																			       'imagecenter','autotypeset',
	        																			       'music']]});
		editor.render(id);
	}
	
	function showContentForEditor(id,cnt){
		//富文本框内容回显
		//让富文本框重新加载
		UE.delEditor(id);
		afluentTextEditor(id);
    	var ue = UE.getEditor(id); 	
        //富文本插件准备好才能回显内容
        ue.addListener("ready", function () {
        	ue.setContent(cnt);
        })
	}
	
	</script>
	
	<script>
	
		function clearNonAuthRes(){
			var permissionList = $('#_permission').val().split(',');
			for(plist in permissionList){
        		if(!(Z.findOne(permissionList,"addOneArticle"))){
        			$('#_add').hide();
        		}
        		if(!(Z.findOne(permissionList,"modifyOneArticle"))){
        			$('._update').hide();
        		}
        		if(!(Z.findOne(permissionList,"removeOneArticle"))){
        			$('._delete').hide();
        		}
        		if(!(Z.findOne(permissionList,"findOneArticle"))){
        			$('._detail').hide();
        		}
        	}
		}
		
		//渲染富文本框
		afluentTextEditor('editor');
		afluentTextEditor('editor1');
		
		layui.use([ 'table', 'layer', 'jquery', 'element', 'form' ],function() {
					var table = layui.table;
					var layer = layui.layer;
					var jquery = layui.jquery;
					var element = layui.element;
					var form = layui.form;
					form.render();
					table.render({
							elem : '#demo',
							toolbar : '#toolbarDemo',
							height : 550,
							page : true,
							url : '${home}/api/admin/business/article/articleList.do' //数据接口
							,
							request : {
								pageName : 'pageNum' //页码的参数名称，默认：page
								,
								limitName : 'pageSize' //每页数据量的参数名，默认：limit
							},
							cols : [ [ //表头
							{
								field : 'article_id',
								title : 'ID',
								sort : true,
								fixed : 'left',
								align : 'center'
							}, {
								field : 'title',
								title : '标题',
								sort : true,
								align : 'center'
							}, {
								field : 'author',
								title : '作者',
								sort : true,
								align : 'center'
							}, {
								field : 'digest',
								title : '摘要',
								sort : true,
								align : 'center'
							}, {
								field : '',
								title : '操作',
								align : 'center',
								toolbar : '#barDemo'
							}, ] ],
							limit : 10,
							done : function(data){
								console.log(data);
								clearNonAuthRes();
							}
					});
					
					//监听头部工具条事件
					table.on('toolbar(opt)', function(obj){
						switch(obj.event){
							case 'add':
						        var index = layer.open({
						            type: 1,
						            title: '新增文章',
						            zIndex: '100',
						            maxmin: true,
						            offset: '100px',
						            area: 'auto',
						            content: $('#pop')
						        });
						    layer.full(index); //全屏
					        break;
						
						};
					});	
					
					//监听行内工具条事件
					table.on('tool(opt)',
							function(obj) {
							    var data = obj.data;
							    switch (obj.event) {
							    case 'detail':
							    	var articleId = eval('('+data.article_id+')');
							    	$.ajax({
						                url: '${home}/api/admin/business/article/findOneArticle.do',
						                type: 'POST',
						                data: JSON.stringify(articleId),
						                contentType: "application/json;charset=utf-8",
						                success: function(data) {
						                    if (data.code == 200) {
						                    	console.log(data.data);
						                    	//将查询出来的值回显
					                    		$('#_title').text(data.data.title);
					                    		$('#_author').text(data.data.author);
					                    		$('#_digest').text(data.data.digest);
					                    		
					                    		var index = layer.open({
										            type: 1,
										            title: '文章详情',
										            maxmin: true,
										            offset: '100px',
										            area: 'auto',
										            content: $('#detailPop')
										        });
						                    } else {
						                    	console.log("查询失败");
						                    }
						                }
						            });
							        layer.full(index); //全屏
							    	break;
							    case 'delete':
							        layer.confirm('确认删除ID为：' + data.article_id + "的文章吗?",
							        function(index) {
							            console.log(data.article_id);
							            articleId = eval('('+data.article_id+')');
							            $.ajax({
							                url: '${home}/api/admin/business/article/removeArticle.do',
							                type: 'POST',
							                data: JSON.stringify(articleId),
							                dataType:'json',
							                contentType:'application/json;charset=utf-8',
							                success: function(data) {
							                    if (data.code == 200) {
							                        obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
							                        layer.msg("删除成功", {
							                            icon: 1,
							                            time: 2000
							                        },function(){
							                        	window.parent.location.href = "${home}/api/admin/sys/login/test.do"
								                        window.location.reload();
							                        });
							                    } else {
							                        layer.msg("删除失败", {
							                            icon: 5,
							                            time: 2000
							                        });
							                    }
							                }
							            });
							            layer.close(index);
							        });
							        break;
							    case 'update':
							    	var articleId = eval('('+data.article_id+')');
							    	$.ajax({
						                url: '${home}/api/admin/business/article/findOneArticle.do',
						                type: 'POST',
						                data: JSON.stringify(articleId),
						                contentType: "application/json;charset=utf-8",
						                success: function(data) {
						                    if (data.code == 200) {
						                    	console.log(data.data);
						                    	//将查询出来的值回显
						                    	form.val("modForm",{
						                    		'title'   : data.data.title,
						                    		'author'  : data.data.author,
						                    		'digest'  : data.data.digest,
						                    		'context' : data.data.context
						                    	})
						                    	$('[name="articleId"]').val(data.data.articleId);
						                    	var cnt = $('[name="context"]').val();
										        showContentForEditor('editor1',cnt);
						                    	var index = layer.open({
										            type: 1,
										            title: '修改用户',
										            zIndex: '100',
										            maxmin: true,
										            offset: '100px',
										            area: 'auto',
										            content: $('#modifyPop'),
										        });
										        layer.full(index); //全屏
						                    } else {
						                    	console.log("查询失败");
						                    }
						                }
						            });
							        break;
							    };
							});

							//监听表单提交事件
							form.on('submit(smt)',
									function(data) {
									    console.log(data.field)
									    //执行重载
									    table.reload('demo', {
									        url: '${home}/api/admin/business/article/articleList.do',
									        page: {
									            curr: 1
									            //重新从第 1 页开始
									        },
									        where: {
									            title: data.field.title
									        }
									    });
									    return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
									    
							});
							
							//监听表单提交事件
							form.on('submit(addSmt)',
									function(data) {
										  console.log(data.field)
									   	  $.ajax({
							                url: '${home}/api/admin/business/article/addArticle.do',
							                type: 'POST',
							                data: JSON.stringify(data.field),
							                contentType: "application/json;charset=utf-8",
							                success: function(data) {
							                    if (data.code == 200) {
							                    	console.log(data)
							                    	layer.msg("添加成功", {
							                            icon: 1,
							                            time: 2000
							                        },function(){
							                        	window.parent.location.href = "${home}/api/admin/sys/login/test.do"
								                        window.location.reload();
							                        });
							                    } else {
							                        layer.msg(data.message, {
							                            icon: 5,
							                            time: 2000
							                        },function(){
							                        	layer.closeAll();
							                        });
							                    }
							                }
							            });
									    return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
							});
							
							//监听表单提交事件
							form.on('submit(modifySmt)',
									function(data) {
										data.field.context = data.field.editorValue;
										delete data.field.editorValue;
									    console.log(data.field)
									    $.ajax({
							                url: '${home}/api/admin/business/article/updateArtilce.do',
							                type: 'POST',
							                data: JSON.stringify(data.field),
							                contentType: "application/json;charset=utf-8",
							                success: function(data) {
							                    if (data.code == 200) {
							                    	console.log(data)
							                    	layer.msg("修改成功", {
							                            icon: 1,
							                            time: 2000
							                        },function(){
							                        	window.parent.location.href = "${home}/api/admin/sys/login/test.do"
								                        window.location.reload();
							                        });
							                    } else {
							                        layer.msg("修改失败", {
							                            icon: 5,
							                            time: 2000
							                        },function(){
							                        	layer.closeAll();
							                        });
							                    }
							                }
							            });
									    return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
							});
							
						}); //layui
						
	</script>
</body>
</html>